package org.myy.learn.hot.二叉树.中序遍历;

import lombok.extern.slf4j.Slf4j;

import java.util.*;

@Slf4j
public class Solution {

    /**
     * 中序遍历
     * @param root
     * @return
     */
    public static List<Integer> inorderTraversal(TreeNode root) {

        List<Integer> list = new ArrayList<>();
        Deque<TreeNode> deque = new LinkedList<>();//当 “栈” 使用  push pop

        while (root != null || !deque.isEmpty()){  //ToDo
            while (root != null){
                deque.push(root);
                root = root.left;
            }
            root = deque.pop();
            list.add(root.val);
            root = root.right;
        }
        return list;
    }

    public static TreeNode buildTree(Integer[] values){
        if (values == null && values.length == 0){return null;}

        TreeNode root = new TreeNode(values[0]);
        Queue<TreeNode> queue = new LinkedList<>();  //对尾入，对首出      FIFO   offer  poll
        queue.offer(root);

        int index = 1;
        //while (!queue.isEmpty() && index < values.length){  //绝对"index < values.length"先不满足
        while (index < values.length){
            TreeNode node = queue.poll(); //队首
            //左节点
            if (index < values.length  &&  values[index] != null){ //ToDo  index < values.length 必须在 values[index]前
                node.left = new TreeNode(values[index]);
                queue.offer(node.left);
            }
            index++;

            //右节点
            if (index < values.length  &&  values[index] != null){
                node.right = new TreeNode(values[index]);
                queue.offer(node.right);
            }
            index++;
        }
        return root;
    }

    public static void main(String[] args) {
        Integer[] values = new Integer[]{1,null,2,3};
        TreeNode root = buildTree(values);
        List<Integer> list = inorderTraversal(root);
        log.info("执行结束，中序遍历={}", list);
    }
}
